import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'tlc_lock_platform_interface.dart';

/// An implementation of [TlcLockPlatform] that uses method channels.
class MethodChannelTlcLock extends TlcLockPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('tlc_lock');
  final eventChannel = const EventChannel("tlc_lock/scan");

  @override
  Future<String?> getPlatformVersion() async {
    final version =
        await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  Future<String?> test() async {
    final version = await methodChannel.invokeMethod<String>('test');
    return version;
  }

  @override
  Future<bool> get isSupported {
    return methodChannel
        .invokeMethod<bool>('isSupported')
        .then((value) => value ?? false);
  }

  @override
  Stream<ScanResult> scan(List<String> services,
      {bool allowDuplicationKeys = false}) {
    return eventChannel.receiveBroadcastStream({
      "services": services,
      "allowDuplicationKeys": allowDuplicationKeys
    }).map((event) {
      return ScanResult(
        name: event["name"],
        identifier: event["identifier"],
      );
    });
  }

  @override
  Future<void> connect(String identifier) async {
    await methodChannel.invokeMethod<void>('connect', identifier);
  }
}
